<?php

namespace app\client\controller\say;

use app\common\controller\Frontend;
use app\common\enums\LearnMeansEnum;
use app\common\enums\say\SayCategoryTypeEnum;
use app\common\model\banxi\say\SayCategory as SayCategoryModel;
use app\common\model\banxi\say\SayGrade;

class SayCategory extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function listCategory()
    {
        $param = $this->request->param(['index', 'limit', "query"]);
        $studentId = $this->auth->id;
        $param['query']['EQ_type'] = SayCategoryTypeEnum::E1;
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $sayCategoryModel = new SayCategoryModel();
        $sayGradeModel = new SayGrade();
        $list = $sayCategoryModel->where($where)->order([
            'sortNum' => 'desc'
        ])->paginate([
            'page' => $pageParams['page'],
            'list_rows' => $pageParams['limit']
        ])->each(function ($item) use ($studentId, $sayGradeModel) {
            if ($item['type'] >= SayCategoryTypeEnum::E2) {
                $item['isLock'] = false;
            } else {
                // 检查是否有课程权限或学习记录
                $checkResult = $sayGradeModel->alias('a')
                    ->join('banxi_say_teach_sentence b', 'a.id = b.gradeId')
                    ->where([
                        'a.sayCategoryId' => $item['id'],
                        'b.del' => 0,
                        'b.parentId' => 0,
                    ])
                    ->where(function ($query) use ($studentId) {
                        $query->whereExists(function ($existsQuery) use ($studentId) {
                            $existsQuery->name('banxi_student_course')
                                ->whereRaw('courseId = b.id')
                                ->where('studentId', $studentId)
                                ->where('del', 0);
                        })->whereOr(function ($query) use ($studentId) {
                            $query->whereExists(function ($existsQuery) use ($studentId) {
                                $existsQuery->name('banxi_learn_say_question_record')
                                    ->whereRaw('sayTeachSentenceId = b.id')
                                    ->where('studentId', $studentId)
                                    ->where('learnMeans', LearnMeansEnum::E1)
                                    ->where('del', 0);
                            });
                        });
                    })->count();
                $item['isLock'] = $checkResult <= 0;
            }
        });
        $this->ok('ok', result_row($list));
    }
}